#include <PA9.h>
#include "filelist.h"
#include <fat.h>
#include <sys/dir.h> 
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

char file_list[256][256]; //file list; up to 256 filenames with 256 characters per filename
char temp_name[32]; //store part of the filename to actually display onscreen
int selected = 0; // the position of the currently selected file
int max = 0; // number of files that have been found
int screen_list_index = 0; //the ONSCREEN selected position
int scroll = 0; //scroll offset

void createlistbox()
{
   max = 0;
   selected = 0;
   max=0;
   screen_list_index=0;
   scroll=0;
   PA_Init8bitBg(1, 3);
   PA_InitText(1,1); //Tell it to use text on background number 1 for the chosen screen
   PA_InitText(0,1); //Tell it to use text on background number 1 for the chosen screen
   PA_SetBgColor(1,PA_RGB(31,31,31)); //set top background color to white
   PA_SetBgColor(0,PA_RGB(31,31,31)); //set bottom background color to white
   PA_SetTextCol(1,0,0,0); //set text color to black
   PA_SetTextCol(0,0,0,0); //set text color to black   
   
  	DIR_ITER* dir;
	dir = diropen ("/CuTiDS/");
	if (dir == NULL) {PA_OutputSimpleText(0,0,0,"Unable to open /CuTiDS/"); PA_OutputSimpleText(0,0,1,"Make sure this folder exists.");}
	struct stat st;
	char filenm[256];
	int i = 0;
	
	while (dirnext(dir, filenm, &st) == 0) {
	   if(!(st.st_mode & S_IFDIR)){// Is a file... or rather, isn't a directory ^^ 
	   	strcpy(file_list[i],filenm); //copy filename into file_list array
			i++;
			max++;
  		}
	}
	sortList(); // sort the filenames
	fillList(); // display the list of files
	if(max==0) PA_OutputSimpleText(0,0,1,"No files found in /CuTiDS/");
	else loadgif();
	
	while(updatelistbox()==0)
	{
	   PA_WaitForVBL();
	}
}

bool updatelistbox()
{ 
   if(Pad.Newpress.Down && selected<max-1)
   {
      selected++;
      if(screen_list_index<=21) screen_list_index++;
      fillList();
      loadgif();
   }
   else if(Pad.Newpress.Up && selected>=0)
   {
      selected--;
      if(screen_list_index>=0) screen_list_index--;
		fillList();
		loadgif();
   }
   else if(Pad.Held.Down)
   {
      int counter = 0;
      while(counter<15 && Pad.Held.Down)
      {
         counter++;
         PA_WaitForVBL();
      }
      while(selected<max-1 && Pad.Held.Down)
      {
         selected++;
         if(screen_list_index<=21) screen_list_index++;
         fillList();
         PA_OutputText(0,0,0,"%d/%d", selected+1, max);
         loadgif();
         PA_WaitForVBL();
         PA_WaitForVBL();
      }
   }
   else if(Pad.Held.Up)
   {
      int counter = 0;
      while(counter<15 && Pad.Held.Up)
      {
         counter++;
         PA_WaitForVBL();
      }
      while(selected>=0 && Pad.Held.Up)
      {
         selected--;
         if(screen_list_index>=0) screen_list_index--;
         fillList();
         PA_OutputText(0,0,0,"%d/%d", selected+1, max);
         loadgif();
         PA_WaitForVBL();
         PA_WaitForVBL();
      }
   }
   else if(Pad.Newpress.B) return true; // exit
   PA_OutputText(0,0,0,"%d/%d", selected+1, max);
   return false;
}

void loadgif()
{
   char file2load[512];
   memset(file2load,0,sizeof(file2load));
	sprintf(file2load,"/CuTiDS/%s",file_list[selected]);
	if(filetype(file2load,".gif"))
	{
		FILE* imgFile = fopen (file2load, "rb");

		if(imgFile){ // Make sure there is a file to load
			// obtain file size:
			u32 imgSize;
			fseek (imgFile, 0 , SEEK_END);
			imgSize = ftell (imgFile);
			rewind (imgFile);
		
			// allocate memory to store the image file
			char * buffer;
			buffer = (char*) malloc (sizeof(char)*imgSize);
			fread (buffer, 1, imgSize, imgFile);
		
			// close the file
			fclose (imgFile);
			PA_LoadGif(1, (void *)buffer);
		}			
	}		
}   

void fillList()
{
   PA_ClearTextBg(0);
	if(screen_list_index<0)
	{
	   screen_list_index = 0;
	   if(scroll>0) scroll--;
	   if(selected<0) selected=0;
	}
   else if(screen_list_index>21)
   {
      screen_list_index=21;
      if(scroll<max-22) scroll++;
      if(selected>max-1) selected=max-1;
   }
	
	int i;
	for(i=0;i<22;i++)
	{
	   strncpy(temp_name,file_list[scroll+i],31);
	   PA_OutputSimpleText(0,1,i+2,temp_name);
	}
	PA_SetTextTileCol(0,TEXT_RED);
	strncpy(temp_name,file_list[selected],31);
	PA_OutputSimpleText(0, 1, screen_list_index+2, temp_name); 
	PA_SetTextTileCol(0,TEXT_BLACK);	
}

void sortList()
{
   qsort(file_list, max, 256, comparator);
}

int comparator( const void * a, const void * b )
{
   return strcmp((const char*)a, (const char*)b);
}

bool filetype(char *filename, char *extention)
{
	if(strstr(strlwr(filename),strlwr(extention)))return 1;
	return 0;
}
